<?php
namespace Shopmanage\Controller;
use Think\Controller;
class WinsController extends ExtendController {
	public function index(){
		$usernick = I("usernick");
		Vendor('Page');
		$type=(int)I("get.type");
		$ctp=I("get.ctp");
		$eid=I("get.eid");
		$ctp=$ctp?$ctp:"all";
		$tools = C("GFT_TYPE");
		if($usernick){
			//必须得到混淆昵称
			$MIX = M("UserMixnick");
			$mixednick = $MIX->where(Array("usernick"=>$usernick))->getField("mixednick");
			if(!$mixednick){
				if(C("TAE")){
					$user_resp = json_decode($fetchService->fetchByGet(C("EWS")."?m=service&c=mixnick&a=get_mixnick&nick=".$usernick));
				}else{
					Vendor("taobaosdk.top.request.MixnickGetRequest");
					$c = new \TopClient;
					$req = new \MixnickGetRequest;
					$req->setNick($this->usernick);
					$c->appkey = C("FT_KEY");
					$c->secretKey = C("FT_SECRET");
					$user_resp = $c->execute($req);
				}
				$mixednick=(string)$user_resp->nick;
				if(C("TAE")){
					$mixednick = urldecode_utf8($mixednick);
				}else{
					$mixednick = urldecode($mixednick);
				}
				$MIX->add(Array("usernick"=>$usernick,"mixednick"=>$mixednick));
			}
		}
		$E = D("UsersGifts");//users_gifts
		$E->sid = $this->sid;
		$E->ctp = $ctp;
		$E->gtype = $type;
		$E->usernick = $usernick;
		$E->mixednick = $mixednick;
		$E->eid = $eid;
		$E->getWhere();
		// $E->where=$where;
		// $E->where=$where." AND (`sm_users_gifts`.`getway`='chouj' OR `sm_users_gifts`.`getway`='shoud' OR `sm_users_gifts`.`getway` IS NULL)";
		$E->usernick=$usernick;
		$E->GetTotal();
		$Page = new \Page($E->total,$this->listRows,Array("usernick"=>$usernick,"eid"=>$eid));
		$Page->rollPage=$this->rollPage;
		$show = $Page->show();
		$E->limit = $Page->firstRow.','.$Page->listRows;
		$data = $E->SendList();
		$this->assign('totalpg',(int)$Page->totalPages);
		$this->assign('curpg',$Page->nowPage);
		$this->assign('page',$show);
		$this->assign('ctp',$ctp);
		$this->assign('tools',$tools);
		$this->assign('data',$data);
		$this->assign('type',$type);
		$this->assign('search',$usernick);
		$this->assign('eid',$eid);
		$this->assign('admin',"wins");
		$this->assign("current","shopwins");
		$this->assign('title','中奖发奖');
		$this->display("Gifts:index");
	}
	public function leadorder_del(){
		$id = I("id");
		$OT = M("Otask");
		$re = $OT->where("`id`=".$id." AND `start_time`='2000-01-01 00:00:00'")->delete();
		if($re){
			$this->success("成功删除任务","/?m=Shopmanage&c=Wins&a=leadorder");
		}else{
			$this->error("该任务已经开始，不能删除！","/?m=Shopmanage&c=Wins&a=leadorder");
		}
	}
	public function leadorder_save(){
		$data["order_start"] = I("start_date");
		$data["order_end"] = I("end_date");
		$data["payment"] = I("payment")?I("payment"):0;
		$data["num_iid"] = I("numiid")?I("numiid"):0;
		$data["order_type"] = I("ordertype");
		$data["creat_time"]=date("Y-m-d H:i:s");
		$data["status"]=0;
		$data["sid"]=session("SID");
		if(!$data["order_start"]){
			$error .= "必须设置开始时间！";
		}
		if(!$data["order_end"]){
			$error .= "必须设置结束时间！";
		}
		if(strtotime($data["order_end"])-strtotime($data["order_start"])>3600*24*30){
			$error .= "一次导入订单不能超过30天！";
		}
		if($error){
			$this->error($error,"/?m=Shopmanage&c=Wins&a=leadorder");
			return;
		}
		$OT = M("Otask");
		$count = $OT->where("`sid`=".session("SID")." AND (`start_time`='2000-01-01 00:00:00' OR `end_time`='2000-01-01 00:00:00')")->getField("count(`id`)");
		if($count>=2){
			$this->error("您还有 $count 个正在排队的导入任务，不能创建更多了！","/?m=Shopmanage&c=Wins&a=leadorder");
		}else{
			$re = $OT->add($data);
			if($re){
				$this->success("创建导入任务成功！","/?m=Shopmanage&c=Wins&a=leadorder");
			}else{
				echo $OT->getDbError();
			}
		}
	}
	public function leadorder(){
		Vendor("taobaosdk.top.request.TmcUserGetRequest");
		$req = new \TmcUserGetRequest;
		$req->setFields("user_nick,topics,user_id,is_valid,created,modified");
		$req->setNick(session("VISITOR_NICK"));
		$resp = $this->c->execute($req);
		$status = $resp->tmc_user->topics->string;
		$OT = M("Otask");
		$re = $OT->where("`sid`=".session("SID"))->getField(
		  "`id`,`order_start`,
		  `order_end`,
		  `order_status`,
		  `num_iid`,
		  `payment`,
		  `rate_level`,
		  `creat_time`,
		  `start_time`,
		  `end_time`,
		  `status`");
		foreach($re as $k=>$v){
			$re[$k]["order_start"]=date("m月d日H时i分",strtotime($re[$k]["order_start"]));
			$re[$k]["order_end"]=date("m月d日H时i分",strtotime($re[$k]["order_end"]));
			$re[$k]["creat_time"]=date("m月d日H时i分",strtotime($re[$k]["creat_time"]));
			if(strtotime($re[$k]["start_time"])==strtotime("2000-01-01 00:00:00")&&strtotime($re[$k]["end_time"])==strtotime("2000-01-01 00:00:00")){
				$re[$k]["status"]="delable";
			}
			if(strtotime($re[$k]["start_time"])<>strtotime("2000-01-01 00:00:00")){
				$re[$k]["start_time"]=date("m月d日H时i分",strtotime($re[$k]["start_time"]));
				$re[$k]["status"]="进行中";
			}else{
				$re[$k]["start_time"]="尚未开始";
			}
			if(strtotime($re[$k]["end_time"])<>strtotime("2000-01-01 00:00:00")){
				$re[$k]["end_time"]=date("m月d日H时i分",strtotime($re[$k]["end_time"]));
				$re[$k]["status"]="已结束";
			}else{
				$re[$k]["end_time"]="尚未结束";
			}
		}
		
		$ORD = M("Orders");
		$tre = $ORD->where("type<>'0'")->order("id desc")->limit(10)->getField("id,pub_time,ts");
		foreach($tre as $k=>$v){
			$ts += strtotime($v["ts"])-strtotime($v["pub_time"]);
		}
		$this->assign("yanchi",out($ts/10)); //订单延迟程度
		$this->assign("status",count($status));
		$this->assign("data",$re);
		$this->assign("title","订单导入");
		$this->assign("current","ddfuwu");
		$this->display();
	}
	public function order(){ 
		$usernick = I("post.usernick");
		$where = $usernick?" AND `buyer_nick`='$usernick'":"";
		Vendor('Page');
		$ORD = M("Orders");
		$total = $ORD->where("`user_id`=".session("VISITOR_ID").$where)->count();
		$Page = new \Page($total,$this->listRows);
		$Page->rollPage=$this->rollPage;
		$show = $Page->show();
		
		$orders = $ORD->where("`user_id`=".session("VISITOR_ID").$where)->limit($Page->firstRow.','.$Page->listRows)->order("pub_time DESC")->getField("id,buyer_nick,payment,oid,pub_time,topic,status");
		
		$CFG = M("ShopCfg");
		$cfg = current($CFG->where("`sid`=".session("SID"))->getField("id,order_payment,order_success_times,order_pay_times"));
		
		$topics = array_merge(C("TOPIC"),C("TOPIC_NEW"));
		foreach($orders as $k=>$order){
			if($orders[$k]["topic"]=="taobao_trade_TradeSuccess"&&$orders[$k]["payment"]>=$cfg["order_payment"]){
				$orders[$k]["tms"] = $cfg["order_success_times"];
			}
			if($orders[$k]["topic"]=="taobao_trade_TradeBuyerPay"&&$orders[$k]["payment"]>=$cfg["order_payment"]){
				$orders[$k]["tms"] = $cfg["order_pay_times"];
			}
			$orders[$k]["topic"]=$topics[$orders[$k]["topic"]];
			$orders[$k]["pub_time"]=date("Y-m-d",strtotime($orders[$k]["pub_time"]));
		}
		$info["type"]="success";
		$info["msg"]="订单系统升级，仅抽过奖的订单号出现在这里。支持3个月以内的订单抽奖。";
		$this->assign('info',$info);
		$this->assign('totalpg',(int)$Page->totalPages);
		$this->assign('curpg',$Page->nowPage);
		$this->assign('page',$show);
		$this->assign("data",$orders);
		$this->assign("title","订单管理");
		$this->assign("current","dingdan");
		$this->display();
	}
	public function order_del(){
		$id = (int)I("get.id");
		$ORD = M("Orders");
		$data["id"]=$id;
		$data["status"] = $ORD->where("`id`=".$id)->delete();
		$this->ajaxReturn($data);
	}
	public function order_add(){
		$topics = C("TOPIC");
		$this->assign("topics",$topics);
		$this->assign("current","dingdan");
		$this->assign("title","添加订单");
		$this->display();
	}
	
	public function order_save(){
		$buyer_nick		= urldecode_utf8(I("post.buyer_nick"));
		$payment		= I("post.payment");
		$oid			= I("post.oid");
		$pub_time		= I("post.pub_time");
		$topic			= I("post.topic");
		$ORD = M("Orders");
		foreach($oid as $k=>$v){
			$data["sid"]=session("SID");
			$data["user_id"]=session("VISITOR_ID");
			$data["user_nick"]=session("VISITOR_NICK");
			$data["buyer_nick"]=$buyer_nick[$k];
			$data["payment"]=$payment[$k];
			$data["oid"]=$oid[$k];	
			$data["tid"]=$oid[$k];	
			$data["pub_time"]=$pub_time[$k];
			$data["topic"]=$topic[$k];
			$data["rate_level"]='';
			$re = $ORD->add($data);
			if($re){
				$msg .= "第 $k 个订单添加成功！";
			}else{
				$msg .= "第 $k 个订单添加失败。。。";
			}
		}
		if($re){
			$this->success($msg,"/?a=order&c=wins&m=shopmanage");
		}else{
			$this->error($msg.$ORD->getDbError(),"/?a=order&c=wins&m=shopmanage");
		}
	}
	public function manual(){
		// 手动从在线订单数据中抽奖
		Vendor('taobaosdk.top.request.TradesSoldGetRequest');
		$start_date = I("post.start_date");
		$end_date = I("post.end_date");
		$start_pay = I("post.start_pay");
		$end_pay = I("post.end_pay");
		$ordertype = I("post.ordertype");
		$count = I("post.count");
		$topics = C("TOPIC_NEW");
		if($count){
			$req = new \TradesSoldGetRequest;
			$req->setFields("seller_nick, buyer_nick,payment,tid,pay_time,status");
			$req->setStartCreated($start_date);
			$req->setEndCreated($end_date);
			$req->setStatus($ordertype);
			// $req->setBuyerNick("zhangsan");
			// $req->setType("game_equipment");
			// $req->setExtType("service");
			// $req->setRateStatus("RATE_UNBUYER");
			// $req->setTag("time_card");
			$req->setPageNo(1);
			$req->setPageSize(1);
			// $req->setUseHasNext("true");
			$resp = $this->c->execute($req, session("access_token"));
			$total = (int)$resp->total_results;
			$retry=0;
			if($total>0){ 
				for($i=0;$i<$count;$i++){
					$lmt = rand(0, $total-1);
					foreach($orders as $k=>$v){
						//已抽出的订单中如果和随机匹配的订单位置相同，则增加一次抽取
						if ($k==$lmt){
							$i--;
							continue;
						}
					}
					if(count($orders)>=$total){
						break;
					}
					$req->setPageNo($lmt);
					$resp = $this->c->execute($req, session("access_token"));
					if($this->usernick=="kekydream"){
					print_r($resp);
					}
					if($resp->trades->trade->payment<$start_pay || $resp->trades->trade->payment> $end_pay){
						$i--;
							$retry++;
					}else{
						$orders[$lmt] = (array)current($resp->trades->trade);
					}
					if($retry>10){
						$i = $count+1;
						break;
					}
					// $orders[$lmt] = current($ORD->where($where)->limit("$lmt,1")->getField("id,buyer_nick,payment,oid,pub_time,topic"));
				}
				foreach($orders as $k=>$order){
					$orders[$k]["topic"]=$topics[$orders[$k]["status"]];
					$orders[$k]["pub_time"]=$orders[$k]["pay_time"]?date("Y-m-d",strtotime($orders[$k]["pay_time"])):"----";
				}
			}
		}
		$this->assign("data",$orders);
		$this->assign("lmt",$lmt);
		$this->assign("total",$total);
		$this->assign("start_date",$start_date);
		$this->assign("end_date",$end_date);
		$this->assign("start_pay",$start_pay);
		$this->assign("end_pay",$end_pay);
		$this->assign("ordertype",$ordertype);
		$this->assign("count",$count);
		$this->assign("topics",$topics);
		$this->assign("title","手动抽奖");
		$this->assign("current","shoudong");
		$this->display();
	}
	public function manual_offline(){
	// 从数据库中抽，废弃
		$start_date = I("post.start_date");
		$end_date = I("post.end_date");
		$start_pay = I("post.start_pay");
		$end_pay = I("post.end_pay");
		$ordertype = I("post.ordertype");
		$count = I("post.count");
		$topics = C("TOPIC");
		if($count){
			$where = "`user_id`=".session("VISITOR_ID");
			$where.= $start_date?" AND `pub_time`>='$start_date'":"";
			$where.= $end_date?" AND `pub_time`<='$end_date'":"";
			$where.= $start_pay?" AND `payment`>='$start_pay'":"";
			$where.= $end_pay?" AND `payment`<='$end_pay'":"";
			$where.= $ordertype?" AND `topic`='$ordertype'":"";
			
			$ORD = M("Orders");
			$total = $ORD->where($where)->getField("count(id)");
			if($total>0){
				for($i=0;$i<$count;$i++){
					$lmt = rand(0, $total-1);
					foreach($orders as $k=>$v){
						if ($k==$lmt){
							$i--;
							continue;
						}
					}
					if(count($orders)>=$total){
						break;
					}
					$orders[$lmt] = current($ORD->where($where)->limit("$lmt,1")->getField("id,buyer_nick,payment,oid,pub_time,topic"));
				}
				foreach($orders as $k=>$order){
					$orders[$k]["topic"]=$topics[$orders[$k]["topic"]];
					$orders[$k]["pub_time"]=date("Y-m-d",strtotime($orders[$k]["pub_time"]));
				}
			}
		}
		$this->assign("data",$orders);
		$this->assign("lmt",$lmt);
		$this->assign("total",$total);
		$this->assign("start_date",$start_date);
		$this->assign("end_date",$end_date);
		$this->assign("start_pay",$start_pay);
		$this->assign("end_pay",$end_pay);
		$this->assign("ordertype",$ordertype);
		$this->assign("count",$count);
		$this->assign("topics",$topics);
		$this->assign("title","手动抽奖");
		$this->assign("current","shoudong");
		$this->display();
	}
	public function checkwl(){
		$gid = I("gid");
		$UG = M("UsersGifts");
		$data = current($UG->where("`id`=".$gid." AND `sid`=".session("SID"))->getField("id,wlid,wlcode"));
		$this->ajaxReturn($data);
	}
	public function fajiang(){
		$gid = I("gid");
		$shop_uid = I("shop_uid");
		$wlcode=I("wlcode");
		$wlid=I("wlid");
		$wlname=I("wlname");
		
		$ADD = M("UserAddress");
		$addwh["sid"]=$this->sid;
		$addwh["shop_uid"]=$shop_uid;
		$add = current($ADD->where($addwh)->getField("`id`,`province`, `city`, `city_part`, `address`, `name`, `tel`"));
		
		$UG = M("UsersGifts");
		$gift = $UG->where("sm_users_gifts.id=".$gid)->join("LEFT JOIN sm_events_gifts ON sm_users_gifts.giftid=sm_events_gifts.id")->getField("giftid AS egid,gift_id as giftid");
		
		$USR = M("ShopUsers");
		$sys_uid = $USR->where(Array("id"=>$shop_uid))->getField("userid");
		
		$LOG = M("GiftsSendlog");
		$adata["sid"] = $this->sid;
		$adata["kxdr_uid"] = 0;
		$adata["shop_uid"] = $shop_uid;
		$adata["sys_uid"] = $sys_uid;
		$adata["ugid"] = $gid;
		$adata["egid"] = key($gift);
		$adata["user_nick"]="";
		$adata["gift_id"]=current($gift);
		$adata["send_time"]=date("Y-m-d H:i:s");
		$adata["is_auto_send"]=0;
		$adata["sender_nick"]=$this->usernick;
		$adata["nationality"]="中国";
		$adata["province"]=$add["province"];
		$adata["city"]=$add["city"];
		$adata["city_part"]=$add["city_part"];
		$adata["address"]=$add["address"];
		$adata["true_name"]=$add["name"];
		$adata["mobile"]=$add["tel"];
		$adata["wlname"]=$wlname;
		$adata["wlid"]=$wlid;
		$adata["wlcode"]=$wlcode;
		$adata["version"]="choujiang";
		$LOG->add($adata);
		
		$data["wlcode"]=$wlcode;
		$data["wlid"]=$wlid;
		$data["status"]=1;
		$data["status"] = $UG->where("`id`=".$gid." AND `sid`=".session("SID"))->save($data);
		$this->ajaxReturn($data);
	}
	public function users(){
		$usernick = I("post.usernick");
		$eventid = I("eid")?I("eid"):0;
		$where = $usernick?" AND `sm_user`.`usernick`='$usernick'":"";
		$where .= " AND `sm_events_users`.`eventid`='$eventid'";
		Vendor('Page');
		$USERS = M("ShopUsers");
		$EU = M("EventsUsers");
		$total = $EU->where("`sid`=".session("SID").$where)->getField("count(`id`)");
		// $total =  $USERS->where("`sm_shop_users`.`sid`=".session("SID").$where)->getField("count(`id`)");
		$Page = new \Page($total,$this->listRows);
		$Page->rollPage=$this->rollPage;
		$show = $Page->show();
		$limit = $Page->firstRow.','.$Page->listRows;
		$users = $USERS->where("`sm_events_users`.`sid`=".session("SID").$where)
					   ->join("LEFT JOIN `sm_user` ON `sm_user`.`id`=`sm_shop_users`.`userid`")
					   ->join("LEFT JOIN `sm_events_users` ON `sm_events_users`.`uzuid`=`sm_shop_users`.`id`")
					   ->limit($limit)
					   ->getField("`sm_events_users`.`id`,`sm_shop_users`.`lotts`,`sm_shop_users`.`wins`,`sm_user`.`usernick`,`sm_user`.`mixednick`,`sm_shop_users`.`addtime`,`sm_events_users`.`score`");
		// foreach($users as $k=>$user){
			// $users[$k]["usernick"] = urldecode_utf8($users[$k]["usernick"]);
		// }
		$this->assign('totalpg',(int)$Page->totalPages);
		$this->assign('curpg',$Page->nowPage);
		$this->assign('page',$show);
		$this->assign("data",$users);
		$this->assign("eid",$eventid);
		$this->assign("title","抽奖用户");
		$this->assign("current","yonghu");
		$this->display();
	}
	public function user_tmsadd(){
		$uid = I("uid");
		$tms = I("tms");
		$EVUSR = M("EventsUsers");
		$data["status"]=$EVUSR->where("`sid`=".session("SID")." AND `id`=".$uid)->setInc("score",$tms);
		$this->ajaxReturn($data);
	}
	public function user_tmsdel(){
		$uid = I("uid");
		$EVUSR = M("EventsUsers");
		$data["score"]=0;
		$data["status"]=$EVUSR->where("`sid`=".session("SID")." AND `id`=".$uid)->save($data);
		$this->ajaxReturn($data);
	}
	public function user_tmsreset(){
	// 高危操作
		$eid = I("eid");
		$EVUSR = M("EventsUsers");
		$data["status"]=$EVUSR->where(Array("sid"=>session("SID"),"eventid"=>$eid))->delete();
		$EV = M("Events");
		$EV->where(Array("sid"=>session("SID"),"eventid"=>$eid))->save(Array("wins"=>0,"lotts"=>0)); //清空中奖和抽奖次数
		$this->ajaxReturn($data);
	}
	public function giftlist_empty(){
		$where="`sm_users_gifts`.`sid`=".session("SID")." AND `eventid`=0";
		$E = M("UsersGifts");
		$E->where($where)->delete();
		$data["lotts"]=0;
		$data["wins"]=0;
		$S = M("ShopCfg");
		$S->where("`sid`=".session("SID"))->save($data);
		$this->success("已经删除所有中奖信息！","/?m=shopmanage&c=wins");
	}
	public function sendaddress_download(){
		$eid = I("eid");
		$EUG = D("EventUserGiftView");
		$EUG->eid = $eid?$eid:0;
		$EUG->sid = $this->sid;
		$EUG->sendaddress_download();
	}
	public function giftlist_download(){
		$eid = I("eid");
		$EUG = D("EventUserGiftView");
		$EUG->eid = $eid?$eid:0;
		$EUG->sid = $this->sid;
		$EUG->gift_list_download();
	}
	public function giftlist_download_old(){
		$tools = C("GFT_TYPE");
		$tools["youhuiq"]=array("name"=>"优惠券","status"=>1,"id"=>2,"tip"=>"填写领取地址");
		$where="`sm_events_gifts`.`sid`=".session("SID");
		$E = D("UsersGifts");//users_gifts
		$E->where=$where;
		$E->GetTotal();
		$data = $E->SendList();
		$str = "奖品类型,奖品等级,中奖数量,奖品价值,奖品名称,中奖人,中奖时间,中奖方式\r\n";   
		foreach($data as $k=>$gift){
			$data[$k]["level"]=getlevel($data[$k]["level"]);
			foreach($tools as $tool){
				if($data[$k]["type"]==$tool["id"]){
					$data[$k]["type"]=strip_tags($tool["name"]);
				}
				if($data[$k]["getway"]=="jifen"){
					$data[$k]["getway"]="积分兑换";
				}
				if($data[$k]["getway"]=="chouj"||empty($data[$k]["getway"])){
					$data[$k]["getway"]="自动抽奖";
				}
				if($data[$k]["getway"]=="shoud"){
					$data[$k]["getway"]="后台抽奖";
				}
				if($data[$k]["getway"]=="qddh"){
					$data[$k]["getway"]="签到兑换";
				}
			}
			$str.=$data[$k]["type"].","
				 .strip_tags($data[$k]["level"]).","
				 .$data[$k]["ugq"]."份,"
				 .$data[$k]["price"]."元,"
				 .$data[$k]["name"].","
				 .$data[$k]["usernick"].","
				 .$data[$k]["wintime"].","
				 .$data[$k]["getway"].","
				 ."\r\n";
		}
		$filename = "中奖信息".date('Ymd').'.csv'; //设置文件名   
		// header("Content-type: application/vnd.ms-excel; charset=gb2312" );
		header("Content-type:text/csv");   
		header("Content-Disposition:attachment;filename=".$filename);   
		header('Cache-Control:must-revalidate,post-check=0,pre-check=0');   
		header('Expires:0');   
		header('Pragma:public');
		
		echo mb_convert_encoding($str,"gb2312","utf-8");  
	}
	
}